#-*- codeing = utf-8 -*-
#@Time : 2020/11/14 15:41
#@Author : 阳某
#@File : my_wsgi_web_server.py
#@Software : PyCharm


from wsgiref.simple_server import  make_server

# 1.路由分发器  ，负责把url匹配到对应的函数
# 2.开发好对应的业务函数
# 3.一个请求来了之后，先走路由分发器，如果找到对应的function，就执行，没有找到就返回404

def book(environ,start_response):
    print('book page')
    start_response('200 OK', [('Content-type', 'text/html;charset=utf-8')])
    return [bytes('<h1>book page!</h1>', encoding='utf-8')]

def cloth(environ,start_response):
    print('cloth page')
    start_response('200 OK', [('Content-type', 'text/html;charset=utf-8')])
    return [bytes('<h1>cloth page!</h1>', encoding='utf-8')]

def url_dispacher():
    urls = {
        '/book':book,
        '/cloth':cloth
    }
    return urls

def run_server(environ,start_response):
    print('hahahah')

    urls = url_dispacher()     #拿到所有的url
    requests_url = environ.get('PATH_INFO')
    print('request url',requests_url)
    if requests_url in urls:
        func = urls[requests_url](environ,start_response)
        return func     #真正返回数据给用户
    else:
        start_response('404',[('Content-type','text/html;charset=utf-8')])
        return [bytes('<h1 style="font-size=50px">Page not Found!!!</h1>',encoding='utf-8')]

if __name__ == '__main__':
    httpd = make_server('localhost',8001,run_server)
    httpd.serve_forever()
